package com.qf.kady.ssm.service.impl;

import com.qf.kady.ssm.entity.ResultVO;
import com.qf.kady.ssm.mapper.UserMapper;
import com.qf.kady.ssm.pojo.User;
import com.qf.kady.ssm.service.UserService;
import com.qf.kady.ssm.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: kady
 * \* Date: 2021/4/21
 * \* Time: 11:50
 * \* 千峰JAVA2101班
 * \* Description: 用户业务层
 * \
 */

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public ResultVO login(User user){
        String loginName = user.getLoginName().trim();
        String password = user.getPassword().trim();
        if(StringUtils.isEmpty(loginName)){
            return ResultVO.error("用户名不能为空！",null);
        }
        if(StringUtils.isEmpty(password)){
            return ResultVO.error("密码不能为空！",null);
        }
        User resUser  = userMapper.findByCondition(user.getLoginName(),null);
        if(ObjectUtils.isEmpty(resUser)){
            return ResultVO.error("该管理员不存在",null);
        }
        if(!MD5Util.md5(password).equals(resUser.getPassword())){
            return ResultVO.error("密码错误",null);
        }
        return ResultVO.ok("登录成功",resUser);
    }

    @Override
    public ResultVO changeWD(String userName, String oldPasswd, String newPasswd) {
        User resUser = userMapper.findByCondition(null,userName);
        if(resUser==null){
            return ResultVO.error("用户不存在",null);
        }
        if(!MD5Util.md5(oldPasswd).equals(resUser.getPassword())){
            return ResultVO.error("原密码错误，请重试",null);
        }
        boolean res = userMapper.updatePassWD(userName, MD5Util.md5(newPasswd));
        return ResultVO.ok("修改成功",null);
    }
}
